package bash

import (
	"math/rand"
	"strconv"
	"strings"
	"time"
)

// 转换字符串为整数
// 增加,分隔符支持
func StringToInt(str string) int {
	b, err := strconv.Atoi(strings.Replace(str, ",", "", -1))
	if err != nil {
		return 0
	}
	return b
}

// 转换字符串为非负整数
func StringToUint(str string) uint {
	return uint(StringToInt(str))
}

// 转换字符串为uint8类型
func StringToUint8(str string) uint8 {
	return uint8(StringToInt(str))
}

// 转换字符串为uint8类型
func StringToInt8(str string) int8 {
	return int8(StringToInt(str))
}

// 转换字符串为uint16型
func StringToUint16(str string) uint16 {
	return uint16(StringToInt(str))
}

// 字符串转长整形int64
// 增加,分隔符支持
func StringToInt64(str string) int64 {
	b, err := strconv.ParseInt(strings.Replace(str, ",", "", -1), 10, 64)
	if err != nil {
		return 0
	}
	return b
}

// 字符串转为uint64类型数字
func StringToUint64(str string) uint64 {
	return uint64(StringToInt64(str))
}

// 字符串转浮点数float64
func StringToFloat64(str string) float64 {
	if str == "" {
		return 0
	}
	out, err := strconv.ParseFloat(strings.Replace(str, ",", "", -1), 64)
	if err != nil {
		return 0
	}
	return out
}

// 字符串转浮点数float32
func StringToFloat32(str string) float32 {
	return float32(StringToFloat64(str))
}

// 生成一个指定长度的随机字符串
func StringToRand(leng uint8) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := uint8(0); i < leng; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

// 生成一个指定长度的随机字符串，字符串中只包含能直接识别出来的字符
func StringToRandPass(leng uint8) string {
	str := "345678abcdefhkmnprstuvwxyABCDEFHKMNPRSTUVWXY"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := uint8(0); i < leng; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

// 字符串首字母转大写
func StringToFirstUpper(str string) string {
	temp := strings.Split(str, "_")
	var upperStr string
	for y := 0; y < len(temp); y++ {
		vv := []rune(temp[y])
		for i := 0; i < len(vv); i++ {
			if i == 0 {
				vv[i] -= 32
				upperStr += string(vv[i])
			} else {
				upperStr += string(vv[i])
			}
		}
	}
	return upperStr
}

// 将字符串格式化成文件名[去除特殊字符]
func StringToFileName(str string) string {
	str = strings.Replace(str, "/", "-", -1)
	str = strings.Replace(str, "\\", "-", -1)
	str = strings.Replace(str, ":", "-", -1)
	str = strings.Replace(str, "*", "", -1)
	str = strings.Replace(str, "\"", "", -1)
	str = strings.Replace(str, "<", "", -1)
	str = strings.Replace(str, ">", "", -1)
	str = strings.Replace(str, "|", "", -1)
	return strings.Replace(str, "?", "", -1)
}
